<template>
	<view class="page">
		<view class="grid-box">
			<view class="grid-item bg-hover" @tap="$goToPage('/pagesCard/friendList/friendList')">
				<u-image width="80rpx" height="80rpx"
					src="https://file.casugn.com/storecompcard/static/img/apply_1681700842934.png"
					mode="scaleToFill"></u-image>
				<text class="grid-item-title">好友申请</text>
				<u-badge max="99" :value="applyNum" bgColor="#F53F3F" absolute :offset="['20rpx','50rpx']"></u-badge>
			</view>
			<view class="grid-item bg-hover" @tap="$goToPage('/pagesParty/party/partyList/partyList')">
				<u-image width="80rpx" height="80rpx"
					src="https://file.casugn.com/storecompcard/static/img/invite_1681700978881.png"
					mode="scaleToFill"></u-image>
				<text class="grid-item-title">组局邀请</text>
				<u-badge max="99" :value="inviteNum" bgColor="#F53F3F" absolute :offset="['20rpx','50rpx']"></u-badge>
			</view>
			<view class="grid-item bg-hover" @tap="$goToPage('/pages/notice/notice')">
				<u-image width="80rpx" height="80rpx"
					src="https://file.casugn.com/storecompcard/static/img/notice_1681700999781.png"
					mode="scaleToFill"></u-image>
				<text class=”>系统通知</text>
				<u-badge max="99" :value="noticeNum" bgColor="#F53F3F" absolute :offset="['20rpx','50rpx']"></u-badge>
			</view>
		</view>

		<template v-if="!wxCheckType">
			<u-tabs :current="tabIndex" :list="tabList" :activeStyle="{color:'#276AEE',fontWeight: 600}" lineColor="#276AEE"
				lineWidth="48rpx" lineHeight="4rpx" :inactiveStyle="{color:'#1D2129',fontWeight: 600}"
				:itemStyle="{ height: '40px' }" @click="(e)=>tabChange(e.index)"></u-tabs>

			<com-search-filter v-model="searchVal" placeholder="请输入"></com-search-filter>

			<u-swipe-action ref="SwipeAction">
				<template v-for="(item,index) in messageListComputed">
					<u-swipe-action-item :key="item.id" :name="item.id" :data-index="item.id" :options="swipeOptions"
						@click.self="(e)=>deleteHandle(e,item,index)">
						<view class="swipe-action" @tap="openChatRoom(item.id,item.name,item.type)">
							<view class="swipe-img" :id="`swipeImg${item.id}`">
								<!-- 单聊 -->
								<u-image v-if="tabIndex===0" width="112rpx" height="112rpx" :src="item.roomIcon"></u-image>
								<!-- 群聊 -->
								<ch-avatar v-if="tabIndex===1" :canvasId="`canvas${item.id}`" :width="112" :gutter="4" :margin="4"
									bgColor="#E5E6EB" :data="item.roomIcon"></ch-avatar>
								<!-- 密聊 -->
								<view v-if="tabIndex===2" class="swipe-img__img" :data-text="item.roomIcon"></view>
								<!-- 未读数量 -->
								<u-badge max="99" :value="item.unreadNumber" bgColor="#F53F3F" absolute
									:offset="['-16rpx','-16rpx']"></u-badge>
							</view>
							<view class="swipe-content">
								<view class="swipe-content-title">
									<text class="swipe-content-title__text"> {{item.name||''}}</text>
									<text v-if="tabIndex!==2" class="swipe-content-title__time">{{item.lastSendTime|chartDatetime}}</text>
								</view>
								<view v-if="item.lastMessage&&tabIndex!==2" class="swipe-content-desc textHide-1">
									<text v-if="item.lastMessageType===0">{{item.lastMessage||''}}</text>
									<text v-else-if="item.lastMessageType===2">[图片]</text>
									<text v-else-if="item.lastMessageType===4">[优惠券]</text>
									<text v-else>[未知类型消息]</text>
								</view>
							</view>
						</view>
					</u-swipe-action-item>
				</template>
			</u-swipe-action>

			<template v-if="loadMoreStatus!=='loading'&&!messageListComputed.length">
				<u-empty marginTop="160rpx" width="240rpx" height="240rpx" text="暂时没有消息" textSize="28rpx" textColor="#86909C"
					icon="https://file.casugn.com/storecompcard/static/img/empty_1681701029306.png"></u-empty>
			</template>

			<cus-add-btn :safeAreaInsetBottom="false" @click="addHandle"></cus-add-btn>
		</template>

		<!-- 系统消息通知列表 -->
		<template v-else>
			<com-notice-list :list="items"></com-notice-list>

			<template v-if="loadMoreStatus!=='loading'&&!items.length">
				<u-empty marginTop="160rpx" width="240rpx" height="240rpx" text="暂时没有通知" textSize="28rpx" textColor="#86909C"
					icon="https://file.casugn.com/storecompcard/temp/空页面@2x(10)_1681113855504.png"></u-empty>
			</template>
		</template>

		<!-- 公用 -->
		<template v-if="loadMoreStatus==='loading'">
			<u-loadmore height="100" fontSize="28rpx" iconSize="34rpx" :status="loadMoreStatus" @loadmore="scrolltolower" />
		</template>

		<!-- 创建聊天室弹窗 -->
		<create-chat-room ref="CreateRhatRoom" :isMultiple="tabIndex!==0" @confirm="createConfirmHandle"></create-chat-room>
	</view>
</template>

<script>
	import { defaultAvatar } from '@/config/staticConfig.js'
	import { mapState, mapGetters } from 'vuex'
	import { nextTick } from "vue"

	export default {
		data() {
			return {
				defaultAvatar,
				tabList: [{
						name: '单聊',
						value: 1,
						badge: {}
					},
					{
						name: '群聊',
						value: 0,
						badge: {}
					},
					{
						name: '密聊',
						value: 4,
						badge: {}
					},
				],
				tabIndex: 0,
				swipeOptions: [{
					icon: 'https://file.casugn.com/storecompcard/static/img/trash_1681701055335.png',
					iconSize: '48rpx',
					style: {
						backgroundColor: '#FFECE8',
					}
				}],
				searchVal: '',

				applyNum: 0, // 好友申请数量
				inviteNum: 0, // 组局邀请数量
				noticeNum: 0, // 系统通知数量

				// 可以共用,不影响
				items: [],
				pageNo: 1,
				pageSize: 20,
				loadMoreStatus: 'nomore', //loading / nomore / loadmore
			}
		},
		computed: {
			...mapState(['wxCheckType']),
			...mapGetters(['userInfo', 'openId']),
			messageListComputed() {
				let tMessageList = JSON.parse(JSON.stringify(this.items))
				if (this.searchVal == '') {
					return tMessageList
				}
				// console.log(tMessageList);
				return tMessageList.filter(item => {
					return item.name.indexOf(this.searchVal) != -1
				})
			},
		},
		onShow() {
			this.queryUnreadNotifyNum()
		},
		onLoad(options) {
			this.loadMoreStatus = 'loading'
			this.pageNo = 1

			if (!this.wxCheckType) {
				this.getDBData()
			} else {
				this.getDBData_notice()
			}

			this.$websocket.onRoomMapChange = (roomMap) => {
				this.items = Object.values(roomMap)
					.filter(item => item.type === this.tabList[this.tabIndex].value)
					.sort((a, b) => {
						return (b.timestamp || 0) - (a.timestamp || 0);
					})
			}

			// 页面刚加载时不触发监听，没找到原因
			this.queryChatMessageNumber()
			this.$websocket.onUnreadCountChange = (unreadCount) => {
				this.$set(this.tabList[0], 'badge', { isDot: !!unreadCount.message_1, value: unreadCount.message_1 })
				this.$set(this.tabList[1], 'badge', { isDot: !!unreadCount.message_0, value: unreadCount.message_0 })
				this.$set(this.tabList[2], 'badge', { isDot: !!unreadCount.message_4, value: unreadCount.message_4 })
			}
		},
		onUnload() {
			this.$websocket.onRoomMapChange = () => {}
			this.$websocket.onUnreadCountChange = () => {}
		},
		onPullDownRefresh() {
			this.refresherrefresh()
			uni.stopPullDownRefresh()
		},
		onReachBottom() {
			this.scrolltolower()
		},
		methods: {
			addHandle() {
				this.$refs.CreateRhatRoom.show()
			},
			tabChange(i) {
				this.tabIndex = i

				this.loadMoreStatus = 'loading'
				this.pageNo = 1
				this.items = []
				this.getDBData()
			},
			async queryChatMessageNumber() {
				let openId = this.openId
				const { result: singleChat } = await this.$api.queryUnreadMessage({ openId, type: 1 })
				const { result: groupChat } = await this.$api.queryUnreadMessage({ openId, type: 0 })
				const { result: secretChat } = await this.$api.queryUnreadMessage({ openId, type: 4 })

				this.tabList[0].badge = { isDot: !!singleChat, value: singleChat || 0, }
				this.tabList[1].badge = { isDot: !!groupChat, value: groupChat || 0, }
				this.tabList[2].badge = { isDot: !!secretChat, value: secretChat || 0, }
			},
			deleteHandle(e, item, index) {
				switch (e.index) {
					case 0:
						// 删除
						this.delChatRoom(item, index)
						break;
				}
			},
			// 删除聊天室
			delChatRoom(item, index) {
				uni.showModal({
					title: '提示',
					content: '确认删除聊天室?',
					success: async (res) => {
						if (res.confirm) {
							let res = await this.$api.delChatRoom(item.id)
							if (res.success) {
								this.$refs.SwipeAction.closeOther()
								this.items.splice(index, 1)
								this.$websocket.deleteRoom(item)
							}
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			//确认创建聊天室
			createConfirmHandle({ roomName, friendList, friendOpenIdList }) {
				let avatarList = [...friendList.map(item => item.head), this.userInfo.head]
				this.createChatRoom(this.tabList[this.tabIndex].value, friendOpenIdList, roomName, avatarList)
			},
			//创建聊天室
			async createChatRoom(type, openIds, roomName, avatarList) {
				let payload = {
					mcChatRoom: {
						createBy: this.openId,
						name: roomName,
						status: 0,
						isDel: 0,
						type: type
					},
					list: [...openIds, this.openId]
				}
				let res = await this.$api.createChatRoom(payload)
				if (res.success) {
					uni.showToast({ title: '创建聊天室成功', icon: 'none' });
					this.openChatRoom(res.result.roomId, roomName, type)

					setTimeout(() => {
						let roomObj = {
							id: res.result.roomId,
							name: roomName,
							type: type,
							chatHead: avatarList[0],
							friendHead: JSON.stringify(avatarList),
							unreadNumber: 0,
							createTime: Date.now()
						}
						this.$websocket.updateRoomMap([roomObj], 'api', 'add')
					}, 100)
				} else {
					uni.showToast({ title: res.message || '创建失败！', icon: 'none' });
				}
			},
			//进入聊天室
			async openChatRoom(roomId, roomName, roomType) {
				// console.log(item);
				uni.navigateTo({
					url: `/pagesParty/chatRoom/chatRoom?roomId=${roomId}&chatTitle=${roomName}&type=${roomType}`
				})
			},
			// 获取头部那些未读数量
			async queryUnreadNotifyNum() {
				let res = await this.$api.queryUnreadNotifyNum({
					openId: this.openId
				})
				if (res.success) {
					this.applyNum = res.result.friendNum
					this.inviteNum = res.result.groupNum
					this.noticeNum = res.result.sysNum
				}
			},
			//查询聊天列表
			async getDBData(type = 'refresh') {
				let payload = {
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					openId: this.openId,
					type: this.tabList[this.tabIndex].value
				}
				let res = await this.$api.queryRobCouponVoucher(payload)
				if (res && res.success) {
					// console.log('列表：', res)
					let tData = res.result.records.map(item => {
						item.friendHead = item.frendHead
						return item
					})
					this.$websocket.updateRoomMap(tData, 'api', type)
					// if (type === 'refresh') {
					// 	this.items = tData
					// }
					// if (type === 'add') {
					// 	this.items.push(...tData)
					// }
					this.loadMoreStatus = res.result.pages > res.result.current ? 'loadmore' : 'nomore'
				} else {
					// uni.showToast({ title: res.message, icon: 'none' })
					this.loadMoreStatus = 'nomore'
				}
			},
			scrolltolower() {
				if (this.loadMoreStatus === 'nomore') {
					return
				}
				this.loadMoreStatus = 'loading';
				this.pageNo += 1

				if (!this.wxCheckType) {
					this.getDBData('add')
				} else {
					this.getDBData_notice('add')
				}
			},
			refresherrefresh() {
				this.loadMoreStatus = 'loading'
				this.items = []
				this.pageNo = 1
				setTimeout(async () => {
					if (!this.wxCheckType) {
						this.getDBData('refresh')
					} else {
						await this.getDBData_notice('refresh')
					}
				}, 500)
			},
			async getDBData_notice(type = 'refresh') {
				let params = {
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					openId: this.openId,
					column: 'createTime',
					order: 'desc',
				}
				let res = await this.$api.getNewsList(params)
				if (res && res.success) {
					let tData = res.result.records
					if (type === 'refresh') {
						this.items = tData
					}
					if (type === 'add') {
						this.items.push(...tData)
					}
					console.log('系统消息列表：', this.items);
					this.loadMoreStatus = res.result.pages > res.result.current ? 'loadmore' : 'nomore'
				} else {
					this.loadMoreStatus = 'nomore'
				}
			},
		},
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #F7F8FA;
	}

	.grid-box {
		background-color: #fff;

		display: flex;
		align-items: center;

		.grid-item {
			position: relative;
			width: 100%;
			padding: 20rpx;
			font-size: 28rpx;
			color: #1D2129;
			line-height: 42rpx;

			display: flex;
			flex-direction: column;
			align-items: center;

			.grid-item-title {
				margin-top: 8rpx;
			}

			::v-deep .u-badge {
				padding: 0 8rpx;
				font-size: 24rpx;
				color: #FFFFFF;
				line-height: 30rpx;
				border: 2rpx solid #FFFFFF;
			}
		}
	}

	::v-deep.u-tabs {
		margin-top: 24rpx;
		background-color: #fff;

		.u-tabs__wrapper__nav__item {
			position: relative;
			padding: 0 32rpx !important;

			.u-badge {
				position: absolute;
				top: 20rpx;
				right: 24rpx;
			}
		}
	}

	.swipe-action {
		position: relative;
		padding: 24rpx 32rpx;
		background-color: #fff;

		display: flex;
		align-items: center;

		&::before {
			content: "";
			position: absolute;
			left: 32rpx;
			right: 32rpx;
			bottom: 0;
			border-bottom: 2rpx solid #E5E6EB;
			transform: scaleY(0.5);
		}

		.swipe-img {
			position: relative;
			margin-right: 20rpx;
			flex: 0 0 auto;

			.swipe-img__img {
				position: relative;
				width: 112rpx;
				height: 112rpx;
				background: #276AEE;
				border-radius: 8rpx;
				border: 2rpx solid #FFFFFF;
				box-sizing: border-box;

				&::before {
					content: attr(data-text);
					position: absolute;
					top: 50%;
					left: 50%;
					font-size: 32rpx;
					font-weight: 500;
					color: #FFFFFF;
					line-height: 44rpx;
					transform: translate(-50%, -50%);
				}
			}

			::v-deep .u-badge {
				padding: 0 8rpx;
				font-size: 24rpx;
				color: #FFFFFF;
				line-height: 30rpx;
				border: 2rpx solid #FFFFFF;
			}
		}

		.swipe-content {
			width: 100%;

			.swipe-content-title {
				display: flex;
				align-items: center;

				.swipe-content-title__text {
					font-size: 32rpx;
					font-weight: 600;
					color: #1D2129;
					line-height: 44rpx;
				}

				.swipe-content-title__time {
					margin-left: auto;
					padding-left: 20rpx;
					font-size: 24rpx;
					color: #86909C;
					line-height: 34rpx;
				}
			}

			.swipe-content-desc {
				margin-top: 16rpx;
				font-size: 24rpx;
				color: #747B84;
				line-height: 36rpx;
			}
		}
	}

	::v-deep.u-swipe-action-item__right__button__wrapper {
		padding: 0 56rpx !important;
	}
</style>
